<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>客户端</title>
		<style type="text/css">
			#client {
				margin: 0px auto;
				width: 500px;
			}

			input {
				width: 80%;
				height: 40px;
				border-radius: 5px;
				border-color: #CCCCCC;
				outline: #01FA01;
			}

			#button {
				width: 84px;
				height: 46px;
				background-color: #5af3a5;
				color: #fff;
				font-size: 20px;
				border-radius: 5px;
				border: none;
				box-shadow: 1px 1px 1px 1px #ccc;
				cursor: pointer;
				outline: #01FA01;
			}
		</style>
	</head>
	<body>
		<div id="client">
			<h1 style="text-align: center;">客户端发送消息</h1>
			<div id="content" contenteditable=true
				style="width: 500px;height: 500px;margin: 0px auto;border: 1px solid #000000;padding: 10px;border-radius: 10px;overflow: auto;">

			</div>
			<div style="padding: 5px 0px">
				<input type="" value="" /> <button id="button" type="button">发送</button>
			</div>
		</div>
		<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
		<script type="text/javascript">
			$(() => {
				var pushData = {
					code: 9002,
					msg: '',
					recId: '',
				};
				var time = null;
				var path = 'ws://127.0.0.1:8009/myHandler/';
				if (typeof(WebSocket) === "undefined") {
					alert('不支持websocket')
					return;
				}
				let id = Math.random(); // 随机数
				// 实例化socket
				var webSocket = new WebSocket(path + '?token=' + id);
				// 监听连接
				webSocket.onopen = function(event) {
					console.log(event);
					interval();
				};
				// 监听消息
				webSocket.onmessage = function(event) {
					let data = JSON.parse(event.data);
					if (data.code == 9002) {
						$('#content').append(
							`<p style="text-align: right;"><span style="color:chocolate;">${data.msg}</span>：服务端</p>`
						)
					} else if (data.code == 9001) {
						$('#content').append(`<p style="color:#a09b9b;text-align:center;" >连接成功</p>`);
					}
					console.log(event)
				};
				// 监听错误
				webSocket.onerror = function(event) {
					console.log(event)
					$('#content').append(`<p style="color:#a09b9b;text-align:center;" >连接错误</p>`);
					clearInterval();
				};
				// 发送消息
				$('#button').click(() => {
					let v = $('input').val();
					if (v) {
						pushData.code = 9002;
						pushData.msg = v;
						webSocket.send(JSON.stringify(pushData));
						$('#content').append(
							`<p>客户端：<span style="color: blueviolet;">${v}</span></p>`
						)
						$('input').val('');
					}

				})

				function interval() {
					time = setInterval(() => {
						pushData.code = 9003;
						pushData.msg = '心跳';
						webSocket.send(JSON.stringify(pushData));
					}, 5000);
				}

				function clearInterval() {
					clearInterval(time);
				}

			})
		</script>
	</body>
</html>
